package com.ksyzt.ksite2.client.column;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
import com.ksyzt.gwt.client.common.GwtUtil;
import com.ksyzt.gwt.client.common.Image64;
import com.ksyzt.gwt.client.event.HasMessageHandlers;
import com.ksyzt.gwt.client.event.MessageEvent;
import com.ksyzt.gwt.client.event.MessageHandler;
import com.ksyzt.ksite2.shared.OrgType;
import com.ksyzt.ksite2.shared.modle.COLUMNObj;

public class ColumnSelector extends DialogBox implements HasMessageHandlers {

	private static ColumnSelectorUiBinder uiBinder = GWT
			.create(ColumnSelectorUiBinder.class);

	interface ColumnSelectorUiBinder extends UiBinder<Widget, ColumnSelector> {
	}

	COLUMNObj m_data;
	private MessageHandler m_tree_click = new MessageHandler() {

		public void onMessage(Object sender, Integer message, Object value) {
			TreeItem it = (TreeItem) value;
			COLUMNObj data = (COLUMNObj) it.getUserObject();
			m_data = data;
			updateState();

			lbCaption.setText(m_data.getNAME());
			lbDesc.setText(m_data.getDESCRIPTION());
			icon.setSrc(GwtUtil.getImageUrl(ColumnEditor.strImagepath,
					m_data.getID()));
		}
	};

	public ColumnSelector() {

		setWidget(uiBinder.createAndBindUi(this));
		setHTML("<b>选择分类</b>");
		tree.setPixelSize(250, 300);
		tree.addMessageHandler(m_tree_click);
		tree.EnableCreate(false);
		updateState();

	}

	protected void updateState() {
		if (m_data == null) {
			btnOK.setEnabled(false);
		} else {
			btnOK.setEnabled(true);
		}

	}

	@UiField
	Button btnOK;
	@UiField
	Button btnCancel;
	@UiField
	ColumnTree tree;

	@UiField
	Label lbCaption;
	@UiField
	Label lbDesc;

	@UiField
	Image64 icon;

	public HandlerRegistration addMessageHandler(MessageHandler handler) {

		return addHandler(handler, MessageEvent.TYPE);
	}

	@UiHandler("btnOK")
	void onOK(ClickEvent e) {
		MessageEvent ev = new MessageEvent(MessageEvent.OK, m_data);
		fireEvent(ev);
	}

	@UiHandler("btnCancel")
	void onCancel(ClickEvent e) {
		MessageEvent ev = new MessageEvent(MessageEvent.CANCEL, m_data);
		fireEvent(ev);
	}

	public void init(int mallid, int orgtype) {

		tree.initTree(mallid, orgtype, OrgType.getOrgNameByType(orgtype), true);
	}

}
